<?php

namespace api\mobile;

use app\common\model\Mobile;
use app\model\MobileOrder;
use think\facade\Db;

class Jing36  extends Duojing36 implements  MobileBillInterface
{

    //文档 https://wodz8x3iow.feishu.cn/wiki/wikcnkVOTzcT9TVwJ0AbjiwtRCb

    /**
    全国三网快充商品编码：G26263330198688SKU26263330204320-50|电信SKU26263330205856-50|移动SKU26263330206880-50|联通SKU26263330207904-100|电信SKU26263330208416-100|移动SKU26263330209440-100|联通SKU26263330210464-200|电信SKU26263330211488-200|移动SKU26263330212512-200|联通

    全国三网慢充商品编码：G25985744355488 SKU25985744361632-50|电信 SKU25985744363168-50|移动 SKU25985744364704-50|联通 SKU25985744366240-100|电信 SKU25985744367776-100|移动 SKU25985744369312-100|联通 SKU25985744374432-200|电信 SKU25985744375968-200|移动 SKU25985744377504-200|联通
     * @var string[]
     */

    private $header = [
        'Content-Type: application/x-www-form-urlencoded',
    ];

    public function create($order)
    {
        /**
         * 历史遗留数组
         * @var array|MobileOrder $order
         */

        $url = $this->info['url'] . '/api/v1/purchaser/order';

        $params = $this->getBaseParams();


        if ($order['order_type'] == 1) {
            //慢充
            return  [
                'status' => BaseModel::RECHARGE_FAIL,
                'remark' => '不支持慢充',
            ];

        }

        $productId = 'G26263330198688';//快充

        $face = fen2yuan($order['amount']);
        //业务信息
        $orderParams = [
            'purchase_no' => $order['sub_order_id'],//买家自己的订单号，必须唯一
            'account' => $order['mobile'],//充值帐户，话费产品就是手机号
            'callbackUrl' => $this->notifyUrl,//回调地址，交易平台根据地址推送结果给买家
            'extend' => json_encode([
                'face' => $face,
                'operator' =>getMobileStr($order['mobile']),
            ],JSON_UNESCAPED_UNICODE),

            'product_id' => $productId,
            'sku_id' => $this->getSkuId($productId,$order['mobile'],$face),
        ];

        $params = array_merge($params,$orderParams);

        $params['sign'] = $this->getSign($params);

        $res = curlPost($url, http_build_query($params), $this->header, 5, true);
        $res = json_decode($res, true);

        $supplier_order_no = '';
        $returnCode = $res['code'] ?? 500;  //code文档 https://wodz8x3iow.feishu.cn/wiki/wikcnE68NGLmM3x6zTGUEJWGpSh
        $remark = $res['message'] ?? '';
        switch ($returnCode) {
            case 200: // 下单成功
            case 40008: // 平台订单号重复，也算成功
                $supplier_order_no = !empty($res['data']['number'])?$res['data']['number']:'';
                $status = self::SUCCESS;
                break;
            case 40015:
                $status = self::LACK_OF_MONEY;
                break;
            case 400://异常报错需要人工去确认
                $status = self::NEED_CONFIRM;
                break;
            default:
                $status = self::FAIL;
                break;
        }

        if (empty($res['code'])){ //返回为空,比如网络延迟
            $status = self::NEED_CONFIRM;
        }

        return compact('status', 'supplier_order_no', 'remark');

    }

    public function queryAmount()
    {
        $url = $this->info['url'] . '/api/v1/capital/balance';

        $params = $this->getBaseParams();

        $params['sign'] = $this->getSign($params);
        $res = curlPost($url, http_build_query($params), $this->header);

        $res = json_decode($res, true);

        if (!isset($res['data']['realBalance'])) {
            return false;
        }

        return yuan2fen($res['data']['realBalance']);
    }

    //待开发----没用到，除非后面需要人工确认的单子
    public function query($orderId)
    {
        $url = $this->info['url'] . '/api/v1/purchaser/query';
        $params = $this->getBaseParams();

        $orderParams = [
            'purchase_no' => $orderId, //买家自己的订单号，和交易平台订单号二选一
//            'number' => '',
        ];

        $params = array_merge($params,$orderParams);

        $params['sign'] = $this->getSign($params);
        $res = curlPost($url, http_build_query($params), $this->header);
        $res = json_decode($res, true);

        return $res;
    }

    public function notify($params)
    {
        $insert = [
            'sub_order_id' => $params['purchase_no'] ?? '',
            'params' => json_encode($params, JSON_UNESCAPED_UNICODE),
            'result' => 'success',
        ];

        $sign = $params['sign'] ?? '';
        $checkSign = $this->getSign($params);
        if ($sign !== $checkSign) {
            $insert['result'] = '验签失败';
            Db::name('mobile_notify')->insert($insert);

            return $insert['result'];
        }

        $order = Db::name('mobile_order')
            ->where('sub_order_id', $params['purchase_no'])
            ->where('mobile_supplier_id', $this->info['id'])
            ->find();
        if (empty($order)) {
            $insert['result'] = '订单不存在';
            Db::name('mobile_notify')->insert($insert);

            return $insert['result'];
        }

        if (in_array($order['supplier_status'], [3, 4, 99])) {
            // if ($order['supplier_status'] == 3 || $order['supplier_status'] == 4) {
            $insert['result'] = '已经成功过';
            Db::name('mobile_notify')->insert($insert);

            return 'success';
        }

        if ($order['supplier_status'] != 2 && $order['supplier_status'] != self::NEED_CONFIRM) {
            $insert['result'] = '订单状态有误：' . $order['supplier_status'];
            Db::name('mobile_notify')->insert($insert);

            return $insert['result'];
        }

        // 供应商订单状态：1订单未创建 2订单已创建 3充值成功 4充值失败
        // 0表示充值中; 1表示已充值; 2表示充值失败;
        $state = $params['state'];

        $supplierStatusMap = [
            3 => 3, // 1已充值 --> 3充值成功
            4 => 3, // 1已充值 --> 3充值成功
//            5 => 4, // 2充值失败 --> 4充值失败
            5 => 99, // 2充值失败 --> 充值失败，等待重试
        ];

        if (empty($supplierStatusMap[$state])){
            $insert['result'] = '状态没找到:'.$state;
            Db::name('mobile_notify')->insert($insert);
            return $insert['result'];
        }

        $supplierStatus = $supplierStatusMap[$state];

        if ($order['supplier_status'] == $supplierStatus) {
            Db::name('mobile_notify')->insert($insert);
            return 'success';
        }
        $update = [
            'supplier_order_no' => $params['number'],
            'supplier_status' => $supplierStatus,
            // 'official_sn' => $params['official_sn'] ?? '',  // 官方流水号
        ];
        $order['official_sn'] = '';
        if ($supplierStatus == 99) {
            $order['notify_url'] = '';  // 失败通知先不发
        } else {
            $update['finish_time'] = time();
        }

        Db::name('mobile_notify')->insert($insert);

        Db::startTrans();
        try {
            // 如果是返佣模式，将订单结算方式改成待结算
            if ($supplierStatus == 3 && $order['settle_type'] == SETTLE_TYPE_PROFIT) {
                if ($order['profit'] == 0) {
                    $update['settle_status'] = 3;
                } elseif ($order['settle_status'] == 1) {
                    $update['settle_status'] = 2;
                }
            }

            Mobile::handleNotify($order, $update);

            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();

            $insert['result'] = '订单更新失败' . $order['id'] . '。' . $e->getMessage();
            Db::name('mobile_notify')->insert($insert);

            return $insert['result'];
        }

        return 'success';
    }

    /**
     * 基础数据
     * @return array
     */
    private function getBaseParams(){
        return [
            'appId' => $this->info['app_id'],
            'timestamp' => bcmul(microtime(true), 1000),
            'version' => 'v1',
        ];
    }

    /**
     * 获取sku
     */
    private function getSkuId($productId,$mobile,$face){

        $phoneType = getMobileStr($mobile);

        $arrs = [
            'G26263330198688'=>'26263330204320-50|电信SKU26263330205856-50|移动SKU26263330206880-50|联通SKU26263330207904-100|电信SKU26263330208416-100|移动SKU26263330209440-100|联通SKU26263330210464-200|电信SKU26263330211488-200|移动SKU26263330212512-200|联通',//快充
            'G25985744355488'=>'25985744361632-50|电信SKU25985744363168-50|移动SKU25985744364704-50|联通SKU25985744366240-100|电信SKU25985744367776-100|移动SKU25985744369312-100|联通SKU25985744374432-200|电信SKU25985744375968-200|移动SKU25985744377504-200|联通',//慢充
        ];

        $newArray = [];
        foreach ($arrs as $pid =>$item){
            foreach (explode('SKU',$item) as $oneStrItem){
                $oneItem = explode('-',$oneStrItem);
                $skuId = $oneItem[0];
                $name = explode('|',$oneItem[1])[1];
                $amount = explode('|',$oneItem[1])[0];

                $newArray[$pid.$name.$amount] = $skuId;
            }
        }

        return $newArray[$productId.$phoneType.$face] ?? '';

    }

}